//
//  FANStatusViewModel.swift
//  Weibo - Swift
//
//  Created by user on 16/4/20.
//  Copyright © 2016年 user. All rights reserved.
//

import UIKit
import SDWebImage

class FANStatusViewModel: NSObject {

//    var statusArray:[FANStatus]?
    
    var statusArray:[FANDataViewModel]?
    
    func loadData(isPull:Bool, finished:(success:Bool ,count:Int)->()){
        
        let urlString = "https://api.weibo.com/2/statuses/friends_timeline.json"
        
        var max_id:Int64 = 0
        
        var since_id:Int64 = 0
        
        if isPull{
            
            max_id = statusArray?.last?.status?.id ?? 0
            
            if max_id != 0{
                
                max_id--
            }
            
        }else{
            
            since_id = statusArray?.first?.status?.id ?? 0
        }
        
        let params = [
            
            "access_token":FANUserNetModel.sharedUserModel.account?.access_token ?? "",
            "max_id": "\(max_id)",
            "since_id": "\(since_id)"
        ]
        
        NetworkTools.sharedTools.request(FANRequestMethod.get, urlString: urlString, parameter: params, progress: nil) { (responseObject, error) -> () in
            
            if  error != nil{
                
                finished(success: false ,count:0)
                
                print(error)
                
                return
            }
            
//            print(responseObject)
            
            
            guard let responseDict = responseObject as? [String:AnyObject] else{
                
                finished(success: false ,count:0)

                return
            }
            
            guard let dicts = responseDict["statuses"] as? [[String:AnyObject]] else{
                
                finished(success: false ,count:0)
                
                return
            }
            
            var tempArray = [FANDataViewModel]()
            
            for value in dicts{
                
                let status = FANStatus(dict: value)
                
                let viewModel = FANDataViewModel()
                
                viewModel.status = status
                
                tempArray.append(viewModel)
            }
            
//            self.statusArray = tempArray

            if self.statusArray == nil{
                
                self.statusArray = [FANDataViewModel]()
            }
            
            if isPull{
                
                self.statusArray = self.statusArray! + tempArray
                
            }else{
                
                self.statusArray = tempArray + self.statusArray!
            }
            
//            finished(success: true)
            
            self.cacheImage(tempArray, finished: finished)
        }
    }
    
    func cacheImage(array:[FANDataViewModel],finished:(success:Bool,count:Int)->()){
        
        let group = dispatch_group_create()
        
        for value in array{
            
            let originalPic_urls = value.status?.pic_urls
            
            let retweetPick_urls = value.status?.retweeted_status?.pic_urls
            
            let pic_urls = (originalPic_urls == nil || originalPic_urls!.count == 0) ? retweetPick_urls : originalPic_urls
                
            if pic_urls?.count == 1{
                
                let urlString = pic_urls?.first?.thumbnail_pic
                
                dispatch_group_enter(group)
                
                SDWebImageManager.sharedManager().downloadImageWithURL(NSURL(string:urlString ?? ""), options: [], progress: nil, completed: { (image, error, _, _, _) -> Void in
                
                    value.calSinglePictureSize(pic_urls)
                
                    dispatch_group_leave(group)
                
                    })
                
            }
            
            
        }
        
        dispatch_group_notify(group, dispatch_get_main_queue(), { () -> Void in
            
            finished(success: true ,count:array.count)
        })
        
    }
    
    
}
